<script setup>
import {ref, onMounted, nextTick, watch} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 活动选项卡
const activeTab = ref('1')

// 查询表单
const queryForm = ref({
  serviceNum: '',
  status: '',
  startDate:'',
  endDate:'',
})

// 表格数据
const tableData = ref([])


const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);


const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchData();
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchData();
}
// 处理状态文本
const getStatusText = (status) => {
  const textMap = {
    1: '待处理',
    2: '已处理',
    3: '已拒绝'
  }
  return textMap[status] || status
}

// 处理状态类型
const getStatusType = (status) => {
  const typeMap = {
    1: 'warning',  // 待处理 - 黄色
    2: 'success',  // 已处理 - 绿色
    3: 'danger'    // 已拒绝 - 红色
  }
  return typeMap[status] || ''
}
const selectedOrders = ref([])

// 处理选择变化
const handleSelectionChange = (selection)=>{
  selectedOrders.value = selection.map(row => row.id);
}

// 重置查询
const resetQuery = () => {
  queryForm.value = {
    serviceNum: '',
    status: '',
    startDate:'',
    endDate:'',
  }
  fetchData()
}

// 执行查询
const handleQuery = () => {
  const params = {
    ...queryForm.value,
    status: queryForm.value.status in statusMap ? statusMap[queryForm.value.status] : queryForm.value.status
  }

  axios.post(`/after/selectByNumAndStatus/${activeTab.value}`, params).then(resp => {
    tableData.value = resp.data
  })
}

// 状态映射表
const statusMap = {
  pending: 1,
  processed: 2,
  rejected: 3
}




const handleTabClick = async () => {
  await nextTick()
  await fetchData(activeTab.value)
}

// 获取数据
const fetchData = async (type = activeTab.value) => {
  try {
    const res = await axios.get(`/after/getAllService/${pageSize.value}/${currentPage.value}/${type}`)
    tableData.value = res.data.data
    total.value = res.data.total
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

// 导出数据
const exportData = () => {
  const ids = selectedOrders.value.length > 0
      ? selectedOrders.value.map(item => item.id)
      : tableData.value.map(item => item.id)

  if (ids.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }

  // 实际项目中应该调用导出API
  window.location.href = `http://localhost:8080/after/download?ids=${selectedOrders.value}`

  ElMessage.success(`已导出 ${ids.length} 条数据`)
  console.log('导出数据ID:', ids)
}

// 删除选中数据
const deleteSelected = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择要删除的数据')
    return
  }

  ElMessageBox.confirm('确定要删除选中的数据吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then( () => {

    // 实际项目中应该调用删除API
     axios.delete(`/after/deleteByIds/${selectedOrders.value}`).then((res)=>{
       fetchData()
       ElMessage.success(res.data)
     })

  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理申请
const handleProcess = (row) => {
  ElMessageBox.prompt('请输入处理意见', '处理申请', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入处理意见'
  }).then(({ value }) => {
    // 实际项目中应该调用处理API
    // await axios.post(`/api/after-sales/${row.id}/process`, { comment: value })

    row.status = 2 // 状态改为已处理
    row.handleTime = new Date().toLocaleString()

    ElMessage.success('处理成功')
  }).catch(() => {
    ElMessage.info('已取消处理')
  })
}

// 查看详情
const viewDetails = (row) => {
  // 这里可以打开详情弹窗或跳转到详情页
  ElMessageBox.alert(`
    <div>
      <p><strong>服务编号：</strong>${row.serviceNum}</p>
      <p><strong>退款账号：</strong>${row.serviceAccount}</p>
      <p><strong>退款金额：</strong>${row.price}¥</p>
      <p><strong>申请时间：</strong>${row.createTime}</p>
      <p><strong>处理时间：</strong>${row.handleTime || '未处理'}</p>
      <p><strong>处理状态：</strong>${getStatusText(row.status)}</p>
    </div>
  `, '申请详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭'
  })
}

// 初始化数据
onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="after-sales-container">
    <div class="header">
      <h2>售后服务</h2>
    </div>

    <!-- 服务类型选项卡 -->
    <el-tabs v-model="activeTab" class="service-tabs" @tab-click="handleTabClick">
      <el-tab-pane label="退款申请" name="1"></el-tab-pane>
      <el-tab-pane label="退货申请" name="2"></el-tab-pane>
      <el-tab-pane label="换货申请" name="3"></el-tab-pane>
    </el-tabs>

    <!-- 查询条件 -->
    <el-card class="query-card">
      <div class="query-title">查询条件</div>
      <el-form :model="queryForm" class="query-form">
        <div class="form-row">
          <el-form-item label="服务编号" class="compact-item">
            <el-input
                v-model="queryForm.serviceNum"
                placeholder="服务编号"
                clearable
                class="compact-input"
            />
          </el-form-item>

          <el-form-item label="处理状态" class="compact-item">
            <el-select
                v-model="queryForm.status"
                placeholder="全部状态"
                clearable
                class="compact-select"
            >
              <el-option label="全部" value="" />
              <el-option label="待处理" value="pending" />
              <el-option label="已处理" value="processed" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
          </el-form-item>

          <el-form-item label="申请日期" class="compact-item">
            <el-date-picker
                v-model="queryForm.startDate"
                type="date"
                placeholder="开始日期"
                value-format="YYYY-MM-DD"
                style="width: 140px"
            />
            <el-date-picker
                v-model="queryForm.endDate"
                type="date"
                placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 140px"
            />
          </el-form-item>

          <el-form-item class="compact-item">
            <el-button type="info" @click="resetQuery" class="action-button">重置</el-button>
            <el-button type="primary" @click="handleQuery" class="action-button">查询</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="exportData">导出数据</el-button>
      <el-button type="danger" @click="deleteSelected" :disabled="selectedOrders.length === 0">删除数据</el-button>
    </div>

    <!-- 退款列表 -->
    <el-card class="list-card">
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            type="selection"
            width="55"
            align="center"
        />
        <el-table-column prop="serviceNum" label="服务编号" width="120" />
        <el-table-column prop="serviceAccount" label="退款账号" width="150" />
        <el-table-column prop="price" label="退款金额" width="120">
          <template #default="{row}">
            {{ row.price }}¥
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180" />
        <el-table-column prop="handleTime" label="处理时间" width="180" />
        <el-table-column prop="status" label="处理状态" width="120">
          <template #default="{row}">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{row}">
            <el-button
                v-if="row.status === 1"
                type="primary"
                size="small"
                @click="handleProcess(row)"
            >
              立即处理
            </el-button>
            <el-button
                v-else
                type="info"
                size="small"
                @click="viewDetails(row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="pagination" >
      <ElPagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[3, 10, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<style scoped>
.after-sales-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
}

.service-tabs {
  margin-bottom: 20px;
}

.query-card {
  margin-bottom: 20px;
}

.query-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.query-form {
  margin-bottom: 0;
}

.action-buttons {
  margin-bottom: 16px;
}

.list-card {
  margin-top: 16px;
}

.el-table {
  margin-top: 16px;
}

.el-form-item {
  margin-right: 20px;
}

.query-form {
  margin-bottom: 0;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px;
}

.compact-item {
  margin-bottom: 0;
  margin-right: 0;
}

.compact-item :deep(.el-form-item__label) {
  padding-right: 8px;
  font-size: 14px;
}

.compact-input {
  width: 180px;
}

.compact-select {
  width: 150px;
}

.compact-date-picker {
  width: 250px;
}

.action-button {
  margin-left: 8px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .form-row {
    gap: 8px;
  }

  .compact-input {
    width: 160px;
  }

  .compact-select {
    width: 140px;
  }

  .compact-date-picker {
    width: 220px;
  }
}

@media (max-width: 992px) {
  .form-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .compact-input,
  .compact-select,
  .compact-date-picker {
    width: 100%;
  }

  .action-button {
    margin-left: 0;
    margin-right: 12px;
  }
}
</style>